package com.koocloud.electroplatemanage.service.impl;

import cn.hutool.core.lang.Validator;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.koocloud.electroplatemanage.auth.mapper.IUserDao;
import com.koocloud.electroplatemanage.common.pojo.ResponseTemplate;
import com.koocloud.electroplatemanage.mapper.IncomeBasicInfoMapper;
import com.koocloud.electroplatemanage.mapper.IncomePartJudgeMapper;
import com.koocloud.electroplatemanage.mapper.MainProductionMapper;
import com.koocloud.electroplatemanage.mapper.ProcessMapper;
import com.koocloud.electroplatemanage.pojo.*;
import com.koocloud.electroplatemanage.pojo.Process;
import com.koocloud.electroplatemanage.pojo.mainpojo.OrderResource;
import com.koocloud.electroplatemanage.pojo.mainpojo.WIP;
import com.koocloud.electroplatemanage.service.ProcessService;
import com.koocloud.electroplatemanage.utils.ListUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import static com.koocloud.electroplatemanage.constant.MainWIPRouteConstant.*;

/**
 * @program: Information_platform
 * @description: 技术要求实现层
 * @author: xxc
 * @create: 2020-11-16 09:57
 */
@Service
@Transactional(rollbackFor=Exception.class)
public class ProcessServiceImpl implements ProcessService {
    @Resource
    private IUserDao iUserDao;
    @Resource
    private ProcessMapper processMapper;
    @Resource
    private MainProductionMapper mainProductionMapper;
    @Resource
    private IncomePartJudgeMapper incomePartJudgeMapper;
    Lock lock = new ReentrantLock();

    /**
     *@Description: 通过工单号查询一条技术要求
     *@Param: [workOrderNumber]
     *@return: com.koocloud.electroplatemanage.common.pojo.ResponseTemplate
     *@Author: xxc
     *@date: 2020/11/16
     */
    @Override
    public ResponseTemplate selectByWorkOrderNumber(String workOrderNumber) {
        try {
            //创建技术要求实体
            Process process = processMapper.selectByWorkOrderNumber(workOrderNumber);
            //判断查表操作是否成功
            if (null != process) {
                //查表成功返回数据
                return ResponseTemplate.builder().code(0).message("查询成功").count(1l).data(process).build();
            } else {
                //查表失败返回提示
                return ResponseTemplate.builder().code(1).message("没有此数据").count(0l).build();
            }
        } catch (Exception e) {
            //遇到异常，返回异常原因
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
        }
    }

    /**
     *@Description: 对技术要求进行全表查询
     *@Param: [page, limit, process]
     *@return: com.koocloud.electroplatemanage.common.pojo.ResponseTemplate
     *@Author: xxc
     *@date: 2020/11/16
     */
    @Override
    public ResponseTemplate selectAllData(String page, String limit, Process process) {
        //校验分页参数是否为纯数字 并且page和limit不都等于0
        if(Validator.isNumber(page)&&Validator.isNumber(limit)&&!("0".equals(page)&&"0".equals(limit))) {
            try {
                lock.unlock();
                int rows = -1;
                //开始查询在工表，状态为3的插入来料基本信息
                List<WIP> wipList= mainProductionMapper.selectAllWIPByLocation(PROCESSPREPARATION);
                if(!StringUtils.isEmpty(wipList)) {
                    for(WIP wip:wipList) {
                        //获取工单号
                        if(!StringUtils.isEmpty(wip.getWorkOrderNumber())) {
                            //数据库重复工单号校验
                            int count = processMapper.selectWorkOrderNumberCount(wip.getWorkOrderNumber());
                            if(count>0) {
                                continue;
                            }
                            String check = "来件按1E0.070.047《表面处理质量检验说明书》的要求进行验收。";
                            String transferWork = "用白纸包装，转到下一工序。";
                            Process insertProcess = new Process();
                            insertProcess.setCheck(check);
                            insertProcess.setTransferWork(transferWork);
                            if(!StringUtils.isEmpty(wip.getEntryPerson())) {
                                //设置制单人
                                insertProcess.setCreator(wip.getEntryPerson());
                            }
                            if(!StringUtils.isEmpty(wip.getEntryTime())) {
                                //设置制单时间
                                insertProcess.setCreateTime(wip.getEntryTime());
                            }
                            String workOrderNumber = wip.getWorkOrderNumber();
                            //设置工单号
                            insertProcess.setWorkOrderNumber(workOrderNumber);

                            rows = processMapper.insert(insertProcess);
                                //记录成功插入条数
                        }
                    }
                }
                //在工表插入完成后开始查询
                if(StringUtils.isEmpty(wipList)||(wipList.size()>0&&rows>0)||(wipList.size()>=0&&rows==-1)) {
                    //开始分页
                    PageHelper.startPage(Integer.valueOf(page), Integer.valueOf(limit));
                    //全局查询
                    List<Process> ProcessList = processMapper.selectAllData(process);
                    //构造分页实体
                    PageInfo<Process> info=new PageInfo<>(ProcessList);
                    if (info.getTotal()>0) {
                        //查询到数据
                        return ResponseTemplate.builder().code(0).message("查询成功").count(info.getTotal()).data(info.getList()).build();
                    } else {
                        //没有查询到数据
                        return ResponseTemplate.builder().code(1).message("没有查到对应数据").count(0l).build();
                    }
                } else {
                    return ResponseTemplate.builder().code(1).message("在工表数据导入失败").count(0l).build();
                }
            } catch (Exception e) {
                //遇到异常，返回异常原因
                e.printStackTrace();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
            }finally {
                lock.unlock();
            }
        } else {
            return ResponseTemplate.builder().code(1).message("分页参数错误").count(0l).build();
        }
    }

    /**
     *@Description: 新增一条技术要求数据
     *@Param: [process, userId]
     *@return: com.koocloud.electroplatemanage.common.pojo.ResponseTemplate
     *@Author: xxc
     *@date: 2020/11/16
     */
    @Override
    public ResponseTemplate insert(Process process, String userId) {
        try{
            lock.lock();
            //获取创建人
            User user = iUserDao.selectByPk(userId);
            //设置创建人
            process.setCreator(user.getJobNum());
            //插入一条记录
            int row = processMapper.insert(process);

            if (row > 0) {
                return ResponseTemplate.builder().code(0).message("插入数据成功").count(1l).build();
            } else {//没有异常并且插入数据失败，原则上不出现
                return ResponseTemplate.builder().code(1).message("插入数据失败").count(0l).build();
            }
        } catch (Exception e) {
            //出现异常返回异常原因
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
        }finally {
            lock.unlock();
        }
    }

    /**
     *@Description: 逻辑删除一条记录
     *@Param: [id, userId, deleteFlag]
     *@return: com.koocloud.electroplatemanage.common.pojo.ResponseTemplate
     *@Author: xxc
     *@date: 2020/11/16
     */
    @Override
    public ResponseTemplate delete(String id, String userId, String deleteFlag) {
        try {
            lock.lock();
            //获取修改人
            User user = iUserDao.selectByPk(userId);
            //逻辑删除一条记录
            int rows = processMapper.delete(id,user.getJobNum(),deleteFlag);
            //判断删除操作是否成功
            if (rows > 0) {
                //删除成功返回数据
                return ResponseTemplate.builder().code(0).message("删除成功").count(1l).build();
            } else {
                //删除失败返回提示
                return ResponseTemplate.builder().code(1).message("删除失败").count(0l).build();
            }
        } catch (Exception e) {
            //遇到异常，返回异常原因
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
        }finally {
            lock.unlock();
        }
    }

    /**
     *@Description: 修改一条技术要求记录
     *@Param: [process, userId]
     *@return: com.koocloud.electroplatemanage.common.pojo.ResponseTemplate
     *@Author: xxc
     *@date: 2020/11/16
     */
    @Override
    public ResponseTemplate update(Process process, String userId) {
        try {
            lock.lock();
            //获取修改人
            User user = iUserDao.selectByPk(userId);
            //设置修改人
            process.setModifier(user.getJobNum());
            process.setDeleteFlag("2");
            //没有异常并且修改数据条数大于0
            int row = processMapper.update(process);
            if(row > 0) {
                return ResponseTemplate.builder().code(0).message("修改数据成功").count(1l).build();
            }
            else {//没有异常并且修改数据失败，原则上不出现
                return ResponseTemplate.builder().code(1).message("修改数据失败").count(0l).build();
            }
        } catch (Exception e) {
            //出现异常返回异常原因
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
        }finally {
            lock.unlock();
        }
    }

    /**
     *@Description: 查询所有表面处理过程  下拉用
     *@Param: []
     *@return: com.koocloud.electroplatemanage.common.pojo.ResponseTemplate
     *@Author: xxc
     *@date: 2020/11/16
     */
    @Override
    public ResponseTemplate selectProcess(String idOrName) {
        try {
            List<CodeNameResult> surfaceProcess = processMapper.selectProcess(idOrName);
            //判断查表操作是否成功
            if (!ListUtil.isEmpty(surfaceProcess)) {
                //查表成功返回数据
                return ResponseTemplate.builder().code(0).message("查询成功").count(1l).data(surfaceProcess).build();
            } else {
                //查表失败返回提示
                return ResponseTemplate.builder().code(1).message("没有此数据").count(0l).build();
            }
        } catch (Exception e) {
            //遇到异常，返回异常原因
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
        }

    }

    /**
     *@Description:  查询所有检验项目   多选用
     *@Param: []
     *@return: com.koocloud.electroplatemanage.common.pojo.ResponseTemplate
     *@Author: xxc
     *@date: 2020/11/16
     */
    @Override
    public ResponseTemplate selectInspect() {
        try {
            List<CodeNameResult> inspect= processMapper.selectInspect();
            //判断查表操作是否成功
            if (!ListUtil.isEmpty(inspect)) {
                //查表成功返回数据
                return ResponseTemplate.builder().code(0).message("查询成功").count(1l).data(inspect).build();
            } else {
                //查表失败返回提示
                return ResponseTemplate.builder().code(1).message("没有此数据").count(0l).build();
            }
        } catch (Exception e) {
            //遇到异常，返回异常原因
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
        }

    }

    /**
     *@Description: 技术要求确认
     *@Param: [workOrderNumber]
     *@return: com.koocloud.electroplatemanage.common.pojo.ResponseTemplate
     *@Author: xxc
     *@date: 2020/11/19
     */
    @Override
    public ResponseTemplate confirmEntryInfo(String workOrderNumber, String userId) {
        try {
            lock.lock();
            //操作人
            User user = iUserDao.selectByPk(userId);
            Date date = new Date();//获取当前的日期
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
            String strDate = df.format(date);//获取String类型的时间
            //改变技术要求表本工单号的状态
            processMapper.changeState(workOrderNumber);

             /*//工单号表
            WorkOrder workOrder = mainProductionMapper.selectWorkOrderByPk(workOrderNumber);
            workOrder.setCurrentLocation(SCHEDULING);
            int limit = mainProductionMapper.updateWorkOrder(workOrder);*/
            //生产在工表
            WIP wip = mainProductionMapper.selectWIPByPk(workOrderNumber);
            wip.setCurrentLocation(SCHEDULING);
            int rows =  mainProductionMapper.updateWIP(wip);
            //生产实际表
            String postion = PROCESSPREPARATION;
            List<OrderResource> orderResourceList = mainProductionMapper.selectOrderResourceByworkOrderNumber(workOrderNumber,postion);
            OrderResource orderResource = orderResourceList.get(0);
            //上一状态完成时间
            orderResource.setCompletionTime(strDate);
            //上一状态完成人
            orderResource.setCompletedPerson(user.getJobNum());
            mainProductionMapper.updateOrderResource(orderResource);
            orderResource.setRoutePosition(SCHEDULING);
            //投入时间
            orderResource.setEntryTime(strDate);
            //投入人
            orderResource.setEntryPerson(user.getJobNum());
            //完成时间
            orderResource.setCompletionTime(null);
            //完成人
            orderResource.setCompletedPerson(null);
            int row = mainProductionMapper.insertOrderResource(orderResource);

            if(rows>0 && row >0) {
                return ResponseTemplate.builder().code(0).message("确认成功").count(1l).build();
            } else {//没有异常并且修改数据失败，原则上不出现
                return ResponseTemplate.builder().code(1).message("确认失败").count(0l).build();
            }
        } catch (Exception e) {
            //遇到异常，返回异常原因
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
        }finally {
            lock.unlock();
        }

    }
}
